#include <iostream>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include "Log.hpp"
#include "Comm.hpp"

const static int defaultbuffersize = 1024;

void Usage(std::string porcess)
{
    std::cout << "usage : \n\t" << porcess << " localip localport " << std::endl;
}

int main(int argc, char *argv[])
{

    if (argc != 3)
    {
        Usage(argv[0]);
        return Usage_Err;
    }

    std::string ip = argv[1];
    uint16_t port = std::atoi(argv[2]);

    // 创建文件细节
    int _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (_sockfd < 0)
    {
        lg(Fatal, "create socket Fail ! erron %d strerror : %s", errno, strerror(errno));
        return Socket_Err;
    }

    lg(Info, "socket create success ! sockfd : %d\n", _sockfd);

    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    server.sin_addr.s_addr = inet_addr(ip.c_str());

    while (true)
    {
        std::cout << "Please Enter@";
        std::string massage;
        // std::getline(std::cin, massage);
        std::cin >> massage;
        ssize_t n = sendto(_sockfd, massage.c_str(), massage.size(), 0, (struct sockaddr *)&server, (socklen_t)sizeof(server));
        if (n > 0)
        {
            // 接受消息
            char buffer[defaultbuffersize];
            struct sockaddr_in temp;
            socklen_t len = sizeof(temp);
            ssize_t m = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&temp, &len);
            if (m > 0)
            {
                buffer[m] = 0;
                std::cout << "Server echo#" << buffer << std::endl;
            }
        }
    }
    close(_sockfd);
    return 0;
}

